package com.itheima.service.db.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.domain.db.*;
import com.itheima.domain.db.Dimensions;
import com.itheima.domain.vo.*;
import com.itheima.mapper.*;
import com.itheima.service.db.TestSoulService;
import com.itheima.service.db.UserInfoService;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.*;

@Service
public class TestSoulServiceImpl implements TestSoulService {

    @Autowired
    private SoulReportMapper soulReportMapper;
    @Autowired
    private SoulPaperMapper soulPaperMapper;
    @Autowired
    private SoulPaperQuestionMapper soulPaperQuestionMapper;
    @Autowired
    private SoulQuestionMapper soulQuestionMapper;
    @Autowired
    private SoulOptionsMapper soulOptionsMapper;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private DimensionMapper dimensionMapper;

    //封装lock和reportid
    @Override
    public List<PaperListVo> queryPaperList(Long userId) {

        //构造返回的页面对象
        PaperListVo paperListVo1 = new PaperListVo();
        PaperListVo paperListVo2 = new PaperListVo();
        PaperListVo paperListVo3 = new PaperListVo();

        //封装问卷
        paddingData(paperListVo1, 1);
        paddingData(paperListVo2, 2);
        paddingData(paperListVo3, 3);

        //根据userid构建查询条件
        QueryWrapper<SoulReport> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        //查询报告集合 用长度来判断是否锁住
        List<SoulReport> soulreports = soulReportMapper.selectList(qw);

        //定义报告id
        int size = soulreports.size();

        //判断报告id
        if (size == 0) {//报告id为空肯定是初级
            //解锁第一个集合
            paperListVo1.setIsLock(0);
            paperListVo2.setIsLock(1);
            paperListVo3.setIsLock(1);
        } else if (soulreports.size() == 1) {
            //解除锁住
            paperListVo1.setIsLock(0);
            paperListVo2.setIsLock(0);
            paperListVo3.setIsLock(1);
            //设置报告id
            for (SoulReport soulreport : soulreports) {
                //查出第一套试卷并且封装reportid , reportid的意义是最后能不能将答题按钮变成查看结果按钮
                if (soulreport.getPaperId() == 1) {
                    paperListVo1.setReportId(soulreport.getId().toString());
                }
                paperListVo2.setReportId(null);
                paperListVo3.setReportId(null);
            }

        } else if (soulreports.size() == 2) {
            //解除锁住
            paperListVo1.setIsLock(0);
            paperListVo2.setIsLock(0);
            paperListVo3.setIsLock(0);
            //设置报告id
            for (SoulReport soulReport : soulreports) {
                if (soulReport.getPaperId() == 1) {
                    paperListVo1.setReportId(soulReport.getId().toString());
                }
                if (soulReport.getPaperId() == 2) {
                    paperListVo2.setReportId(soulReport.getId().toString());
                }
                paperListVo3.setReportId(null);
            }
        } else if (soulreports.size() == 3) {
            //解除锁住
            paperListVo1.setIsLock(0);
            paperListVo2.setIsLock(0);
            paperListVo3.setIsLock(0);
            //设置报告id
            for (SoulReport soulReport : soulreports) {
                if (soulReport.getPaperId() == 1) {
                    paperListVo1.setReportId(soulReport.getId().toString());
                }
                if (soulReport.getPaperId() == 2) {
                    paperListVo2.setReportId(soulReport.getId().toString());
                }
                if (soulReport.getPaperId() == 3) {
                    paperListVo3.setReportId(soulReport.getId().toString());
                }
            }
        }
        //返回集合对象
        List<PaperListVo> list = new ArrayList<>();
        list.add(paperListVo1);
        list.add(paperListVo2);
        list.add(paperListVo3);

        return list;
    }

    //封装每一套试卷
    @Override
    public void paddingData(PaperListVo paperListVo, int i) {
        //设置问卷编号
        paperListVo.setId(String.valueOf(i));
        //设置问卷名称
        paperListVo.setName(soulPaperMapper.selectById(i).getName());
        //设置封面
        paperListVo.setCover(soulPaperMapper.selectById(i).getCover());
        //设置级别
        paperListVo.setLevel(soulPaperMapper.selectById(i).getLevel());
        //设置星别
        paperListVo.setStar(Convert.toInt(soulPaperMapper.selectById(i).getStar()));
        //构建查询条件     <<<<<题目>>>>>
        QueryWrapper<SoulPaperQuestion> qwq = new QueryWrapper<>();
        qwq.eq("paper_id", i);
        //查询后获得各套试卷的对应题目 现在只有题目编号
        List<SoulPaperQuestion> soulPaperQuestions = soulPaperQuestionMapper.selectList(qwq);

        //先建立一个集合用于封装问题
        List<QuestionsVo> questionsVoList = new ArrayList<>();

        //遍历题目1
        for (SoulPaperQuestion soulPaperQuestion : soulPaperQuestions) {
            //把题目加入QuestionsVo对象
            QuestionsVo questionsVo = new QuestionsVo();
            //封装问题序号
            questionsVo.setId(soulPaperQuestion.getQuestionId().toString());
            //封装问题题目
            questionsVo.setQuestion(soulQuestionMapper.selectById(soulPaperQuestion.getQuestionId()).getQuestion());


            //构造查询的条件   <<<<<选项>>>>>
            QueryWrapper<SoulOptions> qwo = new QueryWrapper<>();
            qwo.eq("question_id", soulPaperQuestion.getQuestionId());

            //得到选项的集合
            List<SoulOptions> soulOptionsList = soulOptionsMapper.selectList(qwo);

            //新建选项的集合vo
            List<OptionsVo> optionsVolist = new ArrayList<>();

            //得到optionsVolist集合
            for (SoulOptions soulOptions : soulOptionsList) {
                //新建选项vo
                OptionsVo optionsVo = new OptionsVo();
                //封装选项id
                optionsVo.setId(soulOptions.getId().toString());
                //封装选项
                optionsVo.setOption(soulOptions.getOptions());
                //存入volist
                optionsVolist.add(optionsVo);
            }
            questionsVo.setOptions(optionsVolist);
            questionsVoList.add(questionsVo);
        }
        //封装试题信息
        paperListVo.setQuestions(questionsVoList);
    }
    //提交问卷
    @Override
    public String submitTestPaper(Map<String, List<Answers>> map, Long userid) {
        //计算的分
        Long score = 0L;
        Long questionid = 0L;
        //获得三套题的所有内容
        Collection<List<Answers>> AnswersList = map.values();
        //遍历
        for (List<Answers> answers : AnswersList) {
            //遍历每套题
            for (Answers answer : answers) {
                //获得问题id
                questionid = Long.valueOf(answer.getQuestionId());
                //获得选项字符串
                String option = answer.getOptionId();
                //构建查询条件
                QueryWrapper<SoulOptions> qw = new QueryWrapper<>();
                //根据选项自增长id查询
                qw.eq("id", option);
                //查询得到所有
                SoulOptions souloptions = soulOptionsMapper.selectOne(qw);
                //取到分数然后加起来
                Long score1 = souloptions.getScore();
                score += score1;
            }
        }

        //判断做的是那套试卷  用来取出试卷id
        QueryWrapper<SoulPaperQuestion> qw = new QueryWrapper();
        qw.eq("question_id", questionid);
        SoulPaperQuestion soulpaperquestion = soulPaperQuestionMapper.selectOne(qw);

        //取出试卷id
        Long paperid = soulpaperquestion.getPaperId();

        System.out.println("该用户做的试卷是:" + paperid);
        System.out.println("得分" + score);
        System.out.println("用户" + userid);


        //这个用户能否查到报告id,有id说明要重新测试需要更新得分
        QueryWrapper<SoulReport> qwr = new QueryWrapper<>();
        qwr.eq("user_id", userid).eq("paper_id", paperid);
        SoulReport result = soulReportMapper.selectOne(qwr);

        if (ObjectUtil.isNotEmpty(result)) {
            //不为空就更新得分,最后将id返回
            QueryWrapper<SoulReport> qw1 = new QueryWrapper();
            qw1.eq("user_id", userid).eq("paper_id", paperid);

            //更新分数 和 更新时间
            SoulReport soulreport = new SoulReport();
            soulreport.setScore(score);
            soulreport.setUpdated(new Date(System.currentTimeMillis()));

            //用mapper更新数据库
            soulReportMapper.update(soulreport, qw1);

            //再次查询    整体report结果
            SoulReport soulReport1 = soulReportMapper.selectOne(qw1);

            //返回Stingid
            return soulReport1.getId().toString();
        } else {
            //如果查不到就插入到数据库
            SoulReport soulreport = new SoulReport();
            soulreport.setUserId(userid);
            soulreport.setPaperId(paperid);
            soulreport.setScore(score);
            soulreport.setCreated(new Date(System.currentTimeMillis()));
            soulreport.setUpdated(new Date(System.currentTimeMillis()));
            soulReportMapper.insert(soulreport);

            //查询当前结果id返回
            QueryWrapper<SoulReport> qw3 = new QueryWrapper<>();
            qw3.eq("user_id", userid).eq("paper_id", paperid);
            SoulReport soulreport1 = soulReportMapper.selectOne(qw3);
            System.out.println(soulreport1);
            return soulreport1.getId().toString();
        }
    }

    //查看报告
    @Override
    public ConclusionVo getReport(Long id, Long userId) {
        //创建conclusionVo对象
        ConclusionVo conclusionVo = new ConclusionVo();

        //根据报告id获取report表中数据
        QueryWrapper<SoulReport> qw = new QueryWrapper<>();
        qw.eq("id", id);
        SoulReport soulreport = soulReportMapper.selectOne(qw);
        //取出分数
        Long score = soulreport.getScore();
        //查询分数接近的用户
        QueryWrapper<SoulReport> qw1 = new QueryWrapper<>();
        qw1.between("score",score-8,score+8)
                .ne("user_id",soulreport.getUserId())//排除自己
                .eq("paper_id",soulreport.getPaperId());//同一张试卷
        List<SoulReport> soulreports = soulReportMapper.selectList(qw1);//得到相似分数的人的集合

        //创建一个similar对象集合
        List<SimilarYou> similarYouList = new ArrayList<>();

        //获取他们的id
        //建立一个id集合
        List<Object> userIdList = new ArrayList<>();
        for (SoulReport soulreport1 : soulreports) {
            //得到他们的userid
            Long similaruserId = soulreport1.getUserId();
            //根据userid获得他们的头像
            UserInfo similaruser = userInfoService.findById(similaruserId);

            SimilarYou similarYou = new SimilarYou();
            similarYou.setAvatar(similaruser.getAvatar());
            similarYou.setId(Convert.toInt(similaruser.getId()));//Long转换为Integer
            similarYouList.add(similarYou);
        }

        String[] Key = {"外向", "判断", "抽象", "理性"};
        String[] Value = {"80%", "70%", "90%", "60%"};//80%,70%,90%,60%
        List<Dimensions> d = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            Dimensions d1 = new Dimensions();

            Random r = new Random();
            int ii = r.nextInt(4);
            //获得随机索引

            d1.setKey(Key[ii]);
            d1.setValue(Value[ii]);
            d.add(d1);
        }
        if (score < 21) {

            conclusionVo.setDimensions(d);

            conclusionVo.setConclusion("猫头鹰：他们的共同特质为重计划、条理、细节精准。在行为上，表现出喜欢理性思考与分" +
                    "析、较重视制度、结构、规范。他们注重执行游戏规则、循规蹈矩、巨细靡遗、重视品质、敬业负责。");
            conclusionVo.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/owl.png");
            conclusionVo.setSimilarYou(similarYouList);

        } else if (score >20 && score < 40) {

            conclusionVo.setDimensions(d);

            //2
            conclusionVo.setConclusion("白兔型：平易近人、敦厚可靠、避免冲突与不具批判性。在行为上，表现出不慌不忙、冷静" +
                    "自持的态度。他们注重稳定与中长程规划，现实生活中，常会反思自省并以和谐为中心，即使面对困境，亦能泰然自若，从容应付。");
            //3
            conclusionVo.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/rabbit.png");
            //4
            conclusionVo.setSimilarYou(similarYouList);

        } else if (score > 40 && score < 56) {

            conclusionVo.setDimensions(d);
            //2,3,4
            conclusionVo.setConclusion("狐狸型 ：人际关系能力极强，擅长以口语表达感受而引起共鸣，很会激励并带动气氛。他们喜欢跟别人互动，" +
                    "重视群体的归属感，基本上是比较「人际导向」。由于他们富同理心并乐于分享，具有很好的亲和力，在服务业、销售业、传播业及" +
                    "公共关系等领域中，狐狸型的领导者都有很杰出的表现。");
            conclusionVo.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/fox.png");
            conclusionVo.setSimilarYou(similarYouList);

        } else if (score > 56) {
            conclusionVo.setDimensions(d);
            //234
            conclusionVo.setConclusion("狮子型：性格为充满自信、竞争心强、主动且企图心强烈，是个有决断力的领导者。一般而言，狮子型的人胸" +
                    "怀大志，勇于冒险，看问题能够直指核心，并对目标全力以赴。\n" +
                    "他们在领导风格及决策上，强调权威与果断，擅长危机处理，此种性格最适合开创性与改革性的工作。");
            conclusionVo.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/lion.png");
            conclusionVo.setSimilarYou(similarYouList);

        }
        return conclusionVo;
    }
    //分页问题对象查询
    @Override
    public List<SoulPaper> findSoulTestList() {
        QueryWrapper queryWrapper=new QueryWrapper();
        List<SoulPaper> soulTest = soulPaperMapper.selectList(queryWrapper);
        return soulTest;
    }
    //根据问卷id查询问题列表
    @Override
    public List<SoulQuestion> findSoulQuestionBySid(String sid) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("type",sid);
        List<SoulQuestion> soulQuestions = soulQuestionMapper.selectList(queryWrapper);
        return soulQuestions;
    }
    //根据问题id查询选项列表
    @Override
    public List<SoulOptions> findOptionByQid(Long qid) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("question_id",qid);
        List<SoulOptions> soulOptions = soulOptionsMapper.selectList(queryWrapper);
        return soulOptions;
    }

    //根据id删除问卷
    @Override
    public String deleteSoulQuestionById(String soulQuestionId) {

//        删除问题
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", soulQuestionId);
        soulQuestionMapper.delete(queryWrapper);
        //删除选项
        QueryWrapper queryWrapper2 = new QueryWrapper();
        queryWrapper2.eq("question_id", soulQuestionId);
        soulOptionsMapper.delete(queryWrapper2);

        QueryWrapper queryWrapper1=new QueryWrapper();
        queryWrapper1.eq("question_id",soulQuestionId);
        soulPaperQuestionMapper.delete(queryWrapper1);

        return "删除成功";
    }


    @Override
    public SoulQuestion findSoulQuestionById(String id) {
       return soulQuestionMapper.selectById(id);
    }

    //添加问题
    @Override
    public Long saveSoulQuestion(SoulQuestion newSoulQuestion) {
         soulQuestionMapper.insert(newSoulQuestion);
        return null;
    }

    //添加选项
    @Override
    public String saveOption(SoulOptions newOption) {
        soulOptionsMapper.insert(newOption);
    return null;
    }

    @Override
    public Integer findSoulQuestionId() {
        return soulQuestionMapper.findSoulQuestionId();
    }

    @Override
    public void updateSoulQuestionById(SoulQuestion soulQuestion) {
            soulQuestionMapper.updateById(soulQuestion);
    }

    @Override
    public void updateOptionById(SoulOptions option) {
        soulOptionsMapper.updateById(option);
    }
}
